package cn.edu.scau.dormitory_management_system.service.impl;

import cn.edu.scau.dormitory_management_system.dao.BedDao;
import cn.edu.scau.dormitory_management_system.entity.BedEntity;
import cn.edu.scau.dormitory_management_system.entity.SysLogEntity;
import cn.edu.scau.dormitory_management_system.entity.dto.LogDTO;
import cn.edu.scau.dormitory_management_system.service.BedService;
import cn.edu.scau.dormitory_management_system.service.SysLogService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author whj
 */
@Service("bedService")
public class BedServiceImpl extends ServiceImpl<BedDao, BedEntity> implements BedService {
    private String[] s = {"一","二","三","四","五","六","七","八","九","十"};
    @Autowired(required = false)
    private BedDao bedDao;
    @Override
    public int deleteBed(int dormId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("dorm_id",dormId);
        return  bedDao.deleteByMap(map);
    }

    @Override
    public int insertBed(int dormId, int n) {
        ArrayList<String> strings = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            strings.add(s[i]+"号床");
        }
        return bedDao.insertBed(dormId,strings);
    }

    @Autowired
    private SysLogService logService;
    @Autowired
    private LogDTO logDTO;

    private void addLog(long ms, int sum) {
        SysLogEntity logEntity = new SysLogEntity();
        logEntity.setIpAddr(logDTO.getIp());
        logEntity.setCity(logDTO.getCity());
        logEntity.setUserName(logDTO.getUserName());
        logEntity.setExeTime(ms);
        String op = "";
        if(sum > 1) op = "批量";
        logEntity.setOperation("在表tb_bed中" + op + "插入" + sum + "条记录");
        logEntity.setOpTime(new Date());
        logService.save(logEntity);
    }

    @Override
    public void insertList(List<Integer> ids, List<Integer> n) {
        logDTO.setCan(false);
        Date date = new Date();
        int sum = 0;
        for (int i = 0; i < ids.size(); i++) {
            sum += n.get(i);
            insertBed(ids.get(i), n.get(i));
        }
        addLog(new Date().getTime()-date.getTime(), sum);
        logDTO.setCan(true);
    }
    @Override
    public boolean update(BedEntity bedEntity) {
        return this.baseMapper.updateById(bedEntity) > 0;
    }

    @Override
    public BedEntity getByDormId(int dormId) {
        return bedDao.getByDormId(dormId);
    }

    @Override
    public BedEntity getByStuId(String studentId) {
        return this.baseMapper.selectOne(new QueryWrapper<BedEntity>().eq("stu_id",studentId));
    }
}